package com.yfree.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import com.yfree.YConfig;
import com.yfree.activities.YActivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.UUID;

@SuppressLint("MissingPermission")
public class YDeviceUtils {
    public static String getImei(Context context) {
        try {
            return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        } catch (Exception e) {
            return "";
        }
    }

    public static String getUniqueId(YActivity yActivity) {
        String uniqueId = "android-" + Settings.Secure.getString(yActivity.context.getContentResolver(), Settings.Secure.ANDROID_ID);
        if (yActivity.yBasePath == null) {
            yActivity.yBasePath = yActivity.context.getExternalFilesDir(YConfig.YFreeDir).getAbsolutePath() + YConfig.PROJECTBASEDIR;
            File readyFile = new File(yActivity.yBasePath);
            if (!readyFile.exists())
                if (!readyFile.mkdirs()) return uniqueId;
        }
        String devicePath = yActivity.yBasePath + YConfig.DEVICEPATH + "/";
        File deviceBasePath = new File(devicePath);
        if (!deviceBasePath.exists())
            if (!deviceBasePath.mkdirs()) return uniqueId;
        File file = new File(devicePath + YConfig.DEVICE_FILE_NAME + ".yDevice");
        if (file.exists() && file.canRead() && file.length() > 0)
            try {
                uniqueId = new YAESCrypt().decrypt(new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")).readLine());
            } catch (Exception e) {
                writeFile(file, uniqueId);
            }
        else
            writeFile(file, uniqueId);
        return uniqueId;
    }

    private static void writeFile(File file, String uniqueId) {
        if (file.exists()) file.delete();
        PrintWriter writer = null;
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file.getPath(), true);
            writer = new PrintWriter(outputStream);
            writer.println(new YAESCrypt().encrypt(uniqueId));
        } catch (Exception ignored) {
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (Exception ignored) {
                }
            }
        }
        new File(file.getPath()).setReadOnly();
    }
}
